package cn.xz.kjg.activity

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.os.StrictMode.VmPolicy
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.webkit.*
import androidx.core.content.ContextCompat
import cn.xz.kjg.R
import cn.xz.kjg.base.BaseActivity
import cn.xz.kjg.bean.CommonLib
import cn.xz.kjg.databinding.ActivityWebActBinding
import cn.xz.kjg.net.SendUdp
import cn.xz.kjg.util.ToastUtil
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method


/**
 * 投影界面*/
class WebActActivity : BaseActivity<ActivityWebActBinding>(R.layout.activity_web_act) {

    private val FILECHOOSER_RESULTCODE = 1001

    private var mUploadMessage: ValueCallback<*>? = null

    //标识符
    private var mIP: String? = ""

    private val port = 4051
    private var downTime: Long = 0
    private val states = 0

    override fun initData() {
        super.initData()
        StrictMode.setThreadPolicy(
            ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() // or .detectAll() for all detectable problems
                .penaltyLog()
                .build()
        )
        StrictMode.setVmPolicy(
            VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .penaltyLog()
                .penaltyDeath()
                .build()
        )

        //获取当前设备信息
        mIP = intent.getStringExtra(CommonLib.JUMP_TYPE)
        //如果数据异常直接退出
        if (mIP == null || mIP!!.isNotEmpty()){
            ToastUtil.show("当前数据异常")
            finish()
        }else{
            initWeb()
        }
    }

    private fun initWeb(){
        setUpView("file:///android_asset/spacedesk.html?connectTo=${mIP!!}")
        mDataBind.rlAll.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent): Boolean {
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        var x = event.x.toInt()
                        var y = event.y.toInt()
                        Log.e("x->y:", "$x->$y")
                        y = y - 80
                        y = y * 1920 / 2560
                        x = x * 1920 / 2560
                        val message = downMsg(x, y, 0)
                        SendUdp.send(message,mIP!!, port)
                        downTime = System.currentTimeMillis()
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val moveX = event.x.toInt()
                        val moveY = event.y.toInt()
                        Log.e("move x->y:", "$moveX->$moveY")
                        val moveM = downMsg(moveX, moveY, 1)
                    }
                    MotionEvent.ACTION_UP -> {
                        var upX = event.x.toInt()
                        var upY = event.y.toInt()
                        Log.e("up x->y:", "$upX->$upY")
                        upY = upY - 80
                        upY = upY * 1920 / 2560
                        upX = upX * 1920 / 2560
                        val up = downMsg(upX, upY, 2)
                        SendUdp.send(up,mIP!!, port)
                    }
                }
                return false
            }
        })
    }

    override fun initEvent() {
        super.initEvent()
        mDataBind.tvBack.setOnClickListener {
            mDataBind.rlAll.loadUrl("javascript:app.disconnect()")
            Log.e("x->y", "finish")
            finish()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        android.os.Handler().postDelayed(Runnable {
            for (i in 0..14) {
                SendUdp.send(downMsg(0, 0, 0), mIP!!, port)
                SendUdp.send(downMsg(0, 0, 2), mIP!!, port)
                try {
                    Thread.sleep(50)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }, 1500)
    }

    fun downMsg(x: Int, y: Int, type: Int): String? { //type:0为down,1为移动
        var msg: String? = null
        if (type == 0) {
            msg = "{d=0|$x|$y}"
        } else if (type == 1) {
            msg = "{m=0|$x|$y}"
        } else if (type == 2) {
            msg = "{u=0|$x|$y}"
        }
        return msg
    }

    @SuppressLint("SetJavaScriptEnabled")
    fun setUpView(url: String?) {
        //加载需要显示的网页
//        webView = new WebView(this); 不在xml中创建webview 也可以在这new
//        setContentView(webView);
        mDataBind.rlAll.loadUrl(url!!)
        val webSettings = mDataBind.rlAll.settings
        webSettings.javaScriptEnabled = true //设置WebView属性,运行执行js脚本
        //        webSettings.setSafeBrowsingEnabled(false);
        webSettings.allowContentAccess = true
        webSettings.allowFileAccess = true
        webSettings.domStorageEnabled = true
        webSettings.useWideViewPort = true //设定支持viewport
        webSettings.loadWithOverviewMode = true //自适应屏幕
        webSettings.builtInZoomControls = true
        webSettings.displayZoomControls = false
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.setSupportZoom(true) //设定支持缩放
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE //不读取缓存
        //        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//api 16 不支持
        mDataBind.rlAll.setBackgroundColor(ContextCompat.getColor(this, android.R.color.transparent))
        //        webView.setBackgroundResource(R.color.black);
        mDataBind.rlAll.webViewClient = webClient //设置Web视图
        try { //本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求（less、layui路由）
            if (Build.VERSION.SDK_INT >= 16) {
                val clazz: Class<*> = mDataBind.rlAll.settings.javaClass
                val method: Method? = clazz.getMethod(
                    "setAllowUniversalAccessFromFileURLs", Boolean::class.javaPrimitiveType
                )
                if (method != null) {
                    method.invoke(mDataBind.rlAll.settings, true)
                }
            }
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        }


        // 解决webView 不支持h5 type=file 选择文件弹框
        mDataBind.rlAll.webChromeClient = object : WebChromeClient() {
            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected fun openFileChooser(uploadMsg: ValueCallback<*>?, acceptType: String?) {
                mUploadMessage = uploadMsg
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                i.type = "image/*"
                startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FILECHOOSER_RESULTCODE
                )
            }

            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            override fun onShowFileChooser(
                mWebView: WebView?,
                filePathCallback: ValueCallback<Array<Uri?>?>?,
                fileChooserParams: FileChooserParams?
            ): Boolean {
                return true
            }

            //For Android 4.1 only
            protected fun openFileChooser(
                uploadMsg: ValueCallback<Uri?>?,
                acceptType: String?,
                capture: String?
            ) {
                mUploadMessage = uploadMsg
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.addCategory(Intent.CATEGORY_OPENABLE)
                intent.type = "image/*"
                startActivityForResult(
                    Intent.createChooser(intent, "File Browser"),
                    FILECHOOSER_RESULTCODE
                )
            }

            protected fun openFileChooser(uploadMsg: ValueCallback<Uri?>?) {
                mUploadMessage = uploadMsg
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                i.type = "image/*"
                startActivityForResult(
                    Intent.createChooser(i, "File Chooser"),
                    FILECHOOSER_RESULTCODE
                )
            }
        }
        //XsTestTioStart.startClient();
    }


    var webClient: WebViewClient = object : WebViewClient() {
        //设置打开网页时，不调用系统浏览器进行打开，而是在本WebView中直接显示。
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            //            Toast.makeText(MainActivity.this, "开始加载", Toast.LENGTH_SHORT).show();
            return true
        }

        /*override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
            super.onPageStarted(view, url, favicon)
            //加载开始的操作
        }*/

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            //加载结束的操作
        }

        override fun onReceivedError(
            view: WebView,
            request: WebResourceRequest,
            error: WebResourceError
        ) {
            super.onReceivedError(view, request, error)
            //加载页面的服务器出现错误时（如404）调用
            println("资源加载和页面打开错误时都会进入")
            //回调失败的相关操作
        }

        override fun onReceivedError(
            view: WebView, errorCode: Int,
            description: String, failingUrl: String
        ) {
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mDataBind.rlAll.loadUrl("javascript:app.disconnect()")
            finish()
        }
        return false
    }

}